package com.liu.udpChat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class TalkReceive implements Runnable{
    private int port;
    DatagramSocket socket= null;

    public TalkReceive(int port) {
        this.port = port;
    }

    @Override
    public void run() {

        try {
            socket = new DatagramSocket(this.port);
            while (true){
    //        准备接收包裹
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
                socket.receive(packet);//阻塞式接收包裹
    //            拆分包裹
                String str=new String(packet.getData(),0,packet.getData().length);
    //       如果对方发bye就结束聊天
                if (str.equals("bye")){
                    break;
                }else {
                    System.out.println("对方ip"+packet.getAddress()+"端口"+packet.getPort()+":"+str);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }
}
